package com.caseprocessing.ai.vision;

import com.caseprocessing.ai.AIServiceManager;
import com.caseprocessing.api.*;
import com.caseprocessing.model.CaseDocument;
import com.caseprocessing.model.DocumentType;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * VLM文档视觉分析器
 * 使用视觉-语言模型分析文档的视觉特征
 */
public class VisionDocumentAnalyzer {
    
    private final SiliconFlowClient siliconFlowClient;
    private final VisionPromptLibrary promptLibrary;
    
    public VisionDocumentAnalyzer(SiliconFlowClient siliconFlowClient) {
        this.siliconFlowClient = siliconFlowClient;
        this.promptLibrary = new VisionPromptLibrary();
    }
    
    /**
     * 文档结构视觉分析
     * 识别页眉、正文、签名区域、印章位置等
     */
    public CompletableFuture<DocumentStructureResult> analyzeDocumentStructure(
            List<String> documentImages) {
        
        String prompt = promptLibrary.getStructureAnalysisPrompt();
        
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("system")
                .content(prompt)
                .build(),
            Message.builder()
                .role("user")
                .content("请分析这些文档页面的结构布局，识别关键区域和元素。")
                .build()
        );
        
        return siliconFlowClient.chatCompletionVLM(
            messages, 
            documentImages, 
            ChatCompletionRequest.builder()
                .temperature(0.1)
                .maxTokens(2000)
        ).thenApply(this::parseStructureAnalysisResult);
    }
    
    /**
     * 文档边界检测
     * 智能识别文档分割的视觉边界
     */
    public CompletableFuture<DocumentBoundaryResult> detectDocumentBoundaries(
            List<String> pageImages) {
        
        String prompt = promptLibrary.getBoundaryDetectionPrompt();
        
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("system")
                .content(prompt)
                .build(),
            Message.builder()
                .role("user")
                .content("请分析这些页面，识别文档的分界线和分割点。重点关注：\\n" +
                        "1. 文档标题的变化\\n" +
                        "2. 页面布局的差异\\n" +
                        "3. 内容主题的转换\\n" +
                        "4. 签名印章的分布")
                .build()
        );
        
        return siliconFlowClient.chatCompletionVLM(
            messages, 
            pageImages, 
            ChatCompletionRequest.builder()
                .temperature(0.1)
                .maxTokens(1500)
        ).thenApply(this::parseBoundaryDetectionResult);
    }
    
    /**
     * 文档类型视觉识别
     * 基于视觉特征识别文书类型
     */
    public CompletableFuture<DocumentTypeResult> recognizeDocumentType(
            List<String> documentImages) {
        
        String prompt = promptLibrary.getDocumentTypeRecognitionPrompt();
        
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("system")
                .content(prompt)
                .build(),
            Message.builder()
                .role("user")
                .content("请根据文档的视觉特征识别其类型。关注：\\n" +
                        "1. 文档标题格式\\n" +
                        "2. 内容结构布局\\n" +
                        "3. 印章和签名位置\\n" +
                        "4. 表格和列表格式")
                .build()
        );
        
        return siliconFlowClient.chatCompletionVLM(
            messages, 
            documentImages, 
            ChatCompletionRequest.builder()
                .temperature(0.1)
                .maxTokens(1000)
        ).thenApply(this::parseDocumentTypeResult);
    }
    
    /**
     * 印章和签名检测
     * 检测印章位置、类型和签名完整性
     */
    public CompletableFuture<SealSignatureResult> detectSealsAndSignatures(
            List<String> documentImages) {
        
        String prompt = promptLibrary.getSealSignatureDetectionPrompt();
        
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("system")
                .content(prompt)
                .build(),
            Message.builder()
                .role("user")
                .content("请检测这些文档中的印章和签名：\\n" +
                        "1. 识别印章的位置和类型（公章、财务章、法人章等）\\n" +
                        "2. 检查签名的完整性和位置\\n" +
                        "3. 验证印章和签名的合规性\\n" +
                        "4. 评估印章清晰度和完整性")
                .build()
        );
        
        return siliconFlowClient.chatCompletionVLM(
            messages, 
            documentImages, 
            ChatCompletionRequest.builder()
                .temperature(0.1)
                .maxTokens(1500)
        ).thenApply(this::parseSealSignatureResult);
    }
    
    /**
     * 表格结构识别
     * 识别和分析文档中的表格结构
     */
    public CompletableFuture<TableStructureResult> recognizeTableStructure(
            List<String> documentImages) {
        
        String prompt = promptLibrary.getTableStructurePrompt();
        
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("system")
                .content(prompt)
                .build(),
            Message.builder()
                .role("user")
                .content("请分析文档中的表格结构：\\n" +
                        "1. 识别表格的行列结构\\n" +
                        "2. 提取表头信息\\n" +
                        "3. 分析表格内容类型\\n" +
                        "4. 检测表格完整性")
                .build()
        );
        
        return siliconFlowClient.chatCompletionVLM(
            messages, 
            documentImages, 
            ChatCompletionRequest.builder()
                .temperature(0.1)
                .maxTokens(2000)
        ).thenApply(this::parseTableStructureResult);
    }
    
    /**
     * 页面质量评估
     * 评估扫描页面的质量和可读性
     */
    public CompletableFuture<PageQualityResult> assessPageQuality(
            List<String> pageImages) {
        
        String prompt = promptLibrary.getPageQualityPrompt();
        
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("system")
                .content(prompt)
                .build(),
            Message.builder()
                .role("user")
                .content("请评估这些页面的质量：\\n" +
                        "1. 扫描清晰度\\n" +
                        "2. 文字可读性\\n" +
                        "3. 页面完整性\\n" +
                        "4. 是否存在倾斜、模糊、缺失等问题")
                .build()
        );
        
        return siliconFlowClient.chatCompletionVLM(
            messages, 
            pageImages, 
            ChatCompletionRequest.builder()
                .temperature(0.1)
                .maxTokens(1000)
        ).thenApply(this::parsePageQualityResult);
    }
    
    /**
     * 页面堆叠检测
     * 检测扫描过程中的页面重叠和堆叠问题
     */
    public CompletableFuture<PageStackingResult> detectPageStacking(
            List<String> pageImages) {
        
        String prompt = promptLibrary.getPageStackingPrompt();
        
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("system")
                .content(prompt)
                .build(),
            Message.builder()
                .role("user")
                .content("请检测这些页面是否存在堆叠问题：\\n" +
                        "1. 页面重叠检测\\n" +
                        "2. 内容重复识别\\n" +
                        "3. 页面顺序问题\\n" +
                        "4. 扫描异常检测")
                .build()
        );
        
        return siliconFlowClient.chatCompletionVLM(
            messages, 
            pageImages, 
            ChatCompletionRequest.builder()
                .temperature(0.1)
                .maxTokens(1200)
        ).thenApply(this::parsePageStackingResult);
    }
    
    /**
     * 综合视觉分析
     * 对文档进行全面的视觉分析
     */
    public CompletableFuture<ComprehensiveVisionResult> comprehensiveAnalysis(
            List<String> documentImages) {
        
        // 并行执行多种分析
        CompletableFuture<DocumentStructureResult> structureAnalysis = 
            analyzeDocumentStructure(documentImages);
        
        CompletableFuture<DocumentBoundaryResult> boundaryDetection = 
            detectDocumentBoundaries(documentImages);
        
        CompletableFuture<DocumentTypeResult> typeRecognition = 
            recognizeDocumentType(documentImages);
        
        CompletableFuture<SealSignatureResult> sealSignatureDetection = 
            detectSealsAndSignatures(documentImages);
        
        CompletableFuture<PageQualityResult> qualityAssessment = 
            assessPageQuality(documentImages);
        
        // 等待所有分析完成并整合结果
        return CompletableFuture.allOf(
            structureAnalysis, boundaryDetection, typeRecognition, 
            sealSignatureDetection, qualityAssessment
        ).thenApply(v -> {
            try {
                return new ComprehensiveVisionResult(
                    structureAnalysis.get(),
                    boundaryDetection.get(),
                    typeRecognition.get(),
                    sealSignatureDetection.get(),
                    qualityAssessment.get()
                );
            } catch (Exception e) {
                throw new RuntimeException("综合视觉分析失败", e);
            }
        });
    }
    
    // ============ 结果解析方法 ============
    
    private DocumentStructureResult parseStructureAnalysisResult(ChatCompletionResponse response) {
        String content = response.getFirstChoiceContent();
        // 解析结构化结果，提取区域位置、类型等信息
        return new DocumentStructureResult(content);
    }
    
    private DocumentBoundaryResult parseBoundaryDetectionResult(ChatCompletionResponse response) {
        String content = response.getFirstChoiceContent();
        // 解析边界检测结果，提取分割点信息
        return new DocumentBoundaryResult(content);
    }
    
    private DocumentTypeResult parseDocumentTypeResult(ChatCompletionResponse response) {
        String content = response.getFirstChoiceContent();
        // 解析文档类型识别结果
        return new DocumentTypeResult(content);
    }
    
    private SealSignatureResult parseSealSignatureResult(ChatCompletionResponse response) {
        String content = response.getFirstChoiceContent();
        // 解析印章签名检测结果
        return new SealSignatureResult(content);
    }
    
    private TableStructureResult parseTableStructureResult(ChatCompletionResponse response) {
        String content = response.getFirstChoiceContent();
        // 解析表格结构识别结果
        return new TableStructureResult(content);
    }
    
    private PageQualityResult parsePageQualityResult(ChatCompletionResponse response) {
        String content = response.getFirstChoiceContent();
        // 解析页面质量评估结果
        return new PageQualityResult(content);
    }
    
    private PageStackingResult parsePageStackingResult(ChatCompletionResponse response) {
        String content = response.getFirstChoiceContent();
        // 解析页面堆叠检测结果
        return new PageStackingResult(content);
    }
}